'use strict'
process.env.NODE_ENV = 'production'

const { say } = require('cfonts')
const chalk = require('chalk')
const Multispinner = require('multispinner')

const fs = require('fs')
const path = require('path')
const { exec } = require('child_process')
const rollup = require('rollup')
const pkg = require('pkg')

const servceConfig = require('./rollup.config')
const pack = require('../package.json')
const [, , type] = process.argv

let servers = []

servers.push(
  servceConfig(process.env.NODE_ENV, {
    input: 'src/main.ts',
    output: `${type ? 'pkg' : 'build'}/build.js`,
    isMin: !!type
  })
)

const controllers = fs.readdirSync(path.resolve('./src/controllers'))
for (const controller of controllers) {
  servers.push(
    servceConfig(process.env.NODE_ENV, {
      input: `src/controllers/${controller}`,
      output: `${type ? 'pkg' : 'build'}/controllers/${controller.replace('.ts', '')}.js`,
      isMin: !!type
    })
  )
}

const doneLog = chalk.bgGreen.white(' DONE ') + ' '
const errorLog = chalk.bgRed.white(' ERROR ') + ' '
const okayLog = chalk.bgBlue.white(' OKAY ') + ' '

greeting()

let results = ''
const spinner = new Multispinner(['service'], {
  preText: 'building',
  postText: 'process'
})

spinner.on('success', () => {
  process.stdout.write('\x1B[2J\x1B[0f')
  console.log(`\n\n${results}`)
  console.log(`${okayLog}打包完成 ${chalk.yellow('文件释放在build文件夹中')}\n`)
})

for (const config of servers) {
  rollup.rollup(config).then(handleSuccess).catch(handleCatch)

  function handleSuccess(build) {
    results += `${doneLog}${config.input}构建完成\n\n`
    build.write(config.output).then(() => {
      if (config === servers[servers.length - 1]) executePkg(type === 'pkg')
      spinner.success('service')
    })
  }

  function handleCatch(error) {
    spinner.error('service')
    console.log(`\n${errorLog}${config.input}构建失败`)
    console.error(`\n${error}\n`)
    process.exit(1)
  }
}

// ['node16-linux-x64', 'node16-macos-x64', 'node16-win-x64']
function executePkg(isPkg) {
  if (!isPkg) return

  const packConfig = {
    name: pack.name,
    version: pack.version,
    scripts: {
      start: 'node build.js'
    },
    dependencies: pack.dependencies,
    bin: 'build.js',
    pkg: {
      targets: ['node16-win-x64'], // 'node16-linux-x64', 'node16-macos-x64',
      assets: [],
      scripts: ['build.js', 'controllers/*.js']
    }
  }

  fs.writeFileSync(path.resolve('./pkg/package.json'), JSON.stringify(packConfig, null, 2))

  const command = `pkg pkg/package.json -o pkg/out/${pack.name} -C Brotli`

  const option = {
    cwd: path.resolve()
  }

  exec(command, option, (error, stdout, stderr) => {
    if (error) return console.error(error)
    console.log(stdout)
    console.log(stderr)
    console.log(`${okayLog} ${chalk.yellow(`${pack.name}.exe打包完成`)}\n`)
  })
}

function greeting() {
  const cols = process.stdout.columns
  let text = ''

  if (cols > 85) text = `let's-build`
  else if (cols > 60) text = `let's-|build`
  else text = false

  if (!text) return console.log(chalk.yellow.bold(`\n  let's-build`))

  say(text, {
    colors: ['yellow'],
    font: 'simple3d',
    space: false
  })
}
